package com.bysj.sausys.exception;

import com.bysj.sausys.common.JsonData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SpringExceptionResolver implements HandlerExceptionResolver {

    private final static Logger LOGGER = LoggerFactory.getLogger(SpringExceptionResolver.class);

   @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
       String url = httpServletRequest.getRequestURL().toString();
       ModelAndView mv;
       String defaultMsg = "System error";

       if (e instanceof ParamException) {
           JsonData result = JsonData.fail(e.getMessage());
           mv = new ModelAndView("jsonView", result.toMap());
       } else {
           LOGGER.error("unknow json exception, url:" + url, e);
           JsonData result = JsonData.fail(defaultMsg);
           mv = new ModelAndView("jsonView", result.toMap());
       }

       return mv;
    }
}
